import SingleUpload from '../../common/singleUpload'
import React from 'react'
import {Form, Input,InputNumber, Tooltip, Icon,DatePicker,TimePicker, Cascader, Select, Row, Col, Checkbox, Button } from 'antd';
import '../../../../style/less/formStyle.less'
import '../../../../style/less/editorStyle.less'
import moment from 'moment'
import {inject, observer} from "mobx-react/index";
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/braft.css'
import residences from '../../common/chinaDivision'
import Tip from "../../common/tip"

const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
@inject("store")
@observer
class EditActivities extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            confirmDirty: false
        }
    }
    componentWillReceiveProps=(nextProps)=>{
        if(nextProps.id=="-1"&&this.props.store.id!=nextProps.id){
            this.props.store.id=nextProps.id
            this.props.setIndustry=[]
            this.props.setTags=[]
            this.props.store.actions.getTags()
        }
    }
    componentDidMount() {
        this.props.store.id=this.props.id
        this.props.store.actions.getTags();
        // To disabled submit button at the beginning.
        this.props.form.validateFields();
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.toggle(true)
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                const rangeTimeValue = values['rangeTimePicker'];
                const fieldValues = {
                    ...values,
                    'rangeTimePicker': [
                        rangeTimeValue[0].format('YYYY-MM-DD HH:mm:ss'),
                        rangeTimeValue[1].format('YYYY-MM-DD HH:mm:ss'),
                    ]
                };
                this.props.store.actions.launchActivity(fieldValues,this.props.id,this.props.toggle,this.props.history)
            }
        });
    }
    handleConfirmBlur = (e) => {
        const value = e.target.value;
        this.setState({ confirmDirty: this.state.confirmDirty || !!value });
    }
    hasErrors = (fieldsError) => {
        return Object.keys(fieldsError).some(field => fieldsError[field]);
    }
    getKey = (key)=>{
        this.props.store.activity.imagePath=key
    }
    render() {
        const store=this.props.store
        const activity = store.activity
        const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
        const formItemLayout = {
            labelCol: {
                sm: { span: 4 },
            },
            wrapperCol: {
                sm: { span: 16 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                sm: {
                    span: 8,
                    offset: 4,
                },
            },
        };
        const uploadFn = (param) => {
            const serverURL = '/api/common/upload'
            const xhr = new XMLHttpRequest
            const fd = new FormData()
            // libraryId可用于通过mediaLibrary示例来操作对应的媒体内容
            console.log(param.libraryId)
            const successFn = (response) => {
                // 假设服务端直接返回文件上传后的地址
                // 上传成功后调用param.success并传入上传后的文件地址
                param.success({
                    url: JSON.parse(xhr.responseText).result.finalPath,
                })
            }
            const progressFn = (event) => {
                // 上传进度发生变化时调用param.progress
                param.progress(event.loaded / event.total * 100)
            }
            const errorFn = (response) => {
                // 上传发生错误时调用param.error
                param.error({
                    msg: 'unable to upload.'
                })
            }
            xhr.upload.addEventListener("progress", progressFn, false)
            xhr.addEventListener("load", successFn, false)
            xhr.addEventListener("error", errorFn, false)
            xhr.addEventListener("abort", errorFn, false)
            fd.append('file', param.file)
            xhr.open('POST', serverURL, true)
            xhr.send(fd)
        }
        const editorProps = {
            height: 300,
            contentFormat: 'html',
            media:{
                allowPasteImage: true, // 是否允许直接粘贴剪贴板图片（例如QQ截图等）到编辑器
                image: true, // 开启图片插入功能
                video:false, // 开启视频插入功能
                audio:false, // 开启音频插入功能
                validateFn: null, // 指定本地校验函数，说明见下文
                uploadFn: uploadFn, // 指定上传函数，说明见下文
                removeConfirmFn: null, // 指定删除前的确认函数，说明见下文
                onRemove: null, // 指定媒体库文件被删除时的回调，参数为被删除的媒体文件列表(数组)
                onChange: null, // 指定媒体库文件列表发生变化时的回调，参数为媒体库文件列表(数组)
                onInsert: null, // 指定从媒体库插入文件到编辑器时的回调，参数为被插入的媒体文件列表(数组)
            }
        }
        const activityNameError =  isFieldTouched('activityName') &&getFieldError('activityName');
        const rangetimepickerError =  isFieldTouched('range-time-picker') &&getFieldError('range-time-picker');
        const allowNumError = isFieldTouched('allowNum') &&getFieldError('allowNum');
        const addressError =  isFieldTouched('address') &&getFieldError('address');
        const locationError =  isFieldTouched('location') &&getFieldError('location');
        const streetError =  isFieldTouched('street') &&getFieldError('street');
        const industryError =  isFieldTouched('industry') &&getFieldError('industry');
        const tagsError =  isFieldTouched('tags') &&getFieldError('tags');
        return (
            <div className="edit-activity">
                <Tip title={this.props.id!=-1?"修改活动":"发布活动"}/>
            {((this.props.id=="-1"&&activity.id===undefined)||(this.props.id!=-1&&activity.id==this.props.id))?(
            <Form onSubmit={this.handleSubmit}>
                <FormItem
                    {...formItemLayout}
                    label="活动名称"
                    validateStatus={activityNameError ? 'error' : ''}
                    help={activityNameError || ""}
                >
                    {getFieldDecorator('activityName', {
                        initialValue:activity.activityName,
                        rules: [{ required: true, message: '请输入活动名称!' },{
                            min:5,max:40,message:"活动名称在5到40字"
                        }],
                    })(
                        <Input onBlur={this.handleConfirmBlur}/>
                    )}
                </FormItem>
                <FormItem
                    validateStatus={rangetimepickerError ? 'error' : ''}
                    help={rangetimepickerError || ""}
                    {...formItemLayout}
                    label="活动时间"
                >
                    {getFieldDecorator('rangeTimePicker', {
                        initialValue:activity.startTime?[moment(activity.startTime,'YYYY-MM-DD HH:mm:ss'),moment(activity.endTime,'YYYY-MM-DD HH:mm:ss')]:[],
                        rules: [{ type: 'array', required: true, message: '请输入活动时间!' }],
                    })(
                        <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                    )}
                </FormItem>
                <FormItem
                    validateStatus={allowNumError ? 'error' : ''}
                    help={allowNumError || ""}
                    {...formItemLayout}
                    label="活动规模"
                >
                    {getFieldDecorator('allowNum', {
                        initialValue:activity.allowNum,
                        rules: [{ required: true, message: '请输入活动规模!' }],
                    })(
                        <InputNumber min={1} max={10000} placeholder={"请输入活动人数"}  formatter={value => Math.round(value)} parser={value => Math.round(value)} onBlur={this.handleConfirmBlur}/>
                    )}
                </FormItem>
                <FormItem
                    validateStatus={addressError ? 'error' : ''}
                    help={addressError || ""}
                    {...formItemLayout}
                    label="活动地点"
                >
                    {getFieldDecorator('address', {
                        initialValue: [activity.province, activity.city,activity.area],
                        rules: [{ type: 'array', required: true, message: '请输入活动地点' }],
                    })(
                        <Cascader options={residences} />
                    )}
                </FormItem>
                <FormItem
                    validateStatus={streetError ? 'error' : ''}
                    help={streetError || ""}
                    {...formItemLayout}
                    label="活动详细地点"
                >
                    {getFieldDecorator('street', {
                        initialValue:activity.street,
                        rules: [{ required: true, message: '请输入活动详细地点!', whitespace: false },
                            {min:2,max:60,message:"活动详细地点在2到60字"}],
                    })(
                        <Input placeholder={"如：江东中路300号"} onBlur={this.handleConfirmBlur}/>
                    )}
                </FormItem>
                <FormItem
                    validateStatus={locationError ? 'error' : ''}
                    help={locationError || ""}
                    {...formItemLayout}
                    label="会议地点"
                >
                    {getFieldDecorator('location', {
                        initialValue:activity.location,
                        rules: [{ required: true, message: '请输入会议地点!'},
                            {min:2,max:60,message:"会议地点在2到60字"}],
                    })(
                        <Input placeholder={"如：南京博览中心"} onBlur={this.handleConfirmBlur}/>
                    )}
                </FormItem>
                <SingleUpload getKey={this.getKey} finalPath={store.activity.finalPath} alt={"宣传图:"}/>
                <FormItem
                    validateStatus={industryError ? 'error' : ''}
                    help={industryError || ""}
                    {...formItemLayout}
                    label="行业"
                >
                    <div style={{position:"relative",verticalAlign:"middle",height:"40px"}}>
                        {getFieldDecorator('industry', {
                            initialValue:activity.industry!=null?activity.industry.split(','):null,
                            rules: [{ required: true, message: ''},{
                                validator: (rule,value,callback)=>{
                                    if(store.setIndustry.length===0)
                                        callback("请选择行业！")
                                    callback()
                                }
                            }],
                        })(
                                  <CheckboxGroup  options={store.industry} onChange={(value)=>store.actions.setIndustry(value)} />
                        )}
                    </div>
                </FormItem>
                {/*<div style={{position:"relative",verticalAlign:"middle",height:"40px"}}>*/}
                    {/*<span className="frontitem">行业:</span>*/}
                    {/*<span className="backitem">*/}
                            {/*<div style={{lineHeight:"40px"}}>*/}
                                  {/*<CheckboxGroup  defaultValue={activity.industry!=null?activity.industry.split(','):""} options={store.industry} onChange={(value)=>store.actions.setIndustry(value)} />*/}
                            {/*</div>*/}
                        {/*</span>*/}
                {/*</div>*/}
                <FormItem
                    validateStatus={tagsError ? 'error' : ''}
                    help={tagsError || ""}
                    {...formItemLayout}
                    label="标签"
                >
                    <div style={{position:"relative",verticalAlign:"middle",height:"40px"}}>
                        {getFieldDecorator('tags', {
                            initialValue:activity.tags!=null?activity.tags:null,
                            rules: [{ required: true, message: ''},{
                                validator: (rule,value,callback)=>{
                                    if(store.setTags.length===0)
                                        callback("请选择标签！")
                                    callback()
                                }
                            }],
                        })(
                            <CheckboxGroup  options={store.tags} onChange={(value)=>store.actions.setTags(value)} />
                        )}
                    </div>
                </FormItem>
                {/*<FormItem*/}
                {/*{...formItemLayout}*/}
                {/*label="活动费用"*/}
                {/*>*/}
                {/*{getFieldDecorator('price', {*/}
                {/*rules: [{ required: true, message: '请输入活动价格，免费为0!' }],*/}
                {/*})(*/}
                {/*<Input placeholder={"请输入活动价格，免费为0"} onBlur={this.handleConfirmBlur} />*/}
                {/*)}*/}
                {/*</FormItem>*/}
                <div style={{position:"relative",verticalAlign:"middle",marginBottom:"30px"}}>
                    <span className="frontitem2">组织架构:</span>
                    <span className="backitem2">
                        <div className="editor-wrapper">
                            <BraftEditor {...editorProps} initialContent={activity.organizations}
                                         onChange={(content)=>{activity.organizations=content;console.log(activity.organizations)}}/>
                        </div>
                    </span>
                </div>
                <div style={{position:"relative",verticalAlign:"middle",marginBottom:"30px"}}>
                    <span className="frontitem2">活动内容:</span>
                    <span className="backitem2">
                         <div className="editor-wrapper">
                                <BraftEditor {...editorProps} initialContent={activity.activityContent}
                                             onChange={(content)=>{activity.activityContent=content}}/>
                            </div>
                        </span>
                </div>
                <div style={{position:"relative",verticalAlign:"middle",marginBottom:"30px"}}>
                    <span className="frontitem2">主办方介绍:</span>
                    <span className="backitem2">
                          <div className="editor-wrapper">
                                <BraftEditor {...editorProps} initialContent={activity.introduce}
                                             onChange={(content)=>{activity.introduce=content}}/>
                            </div>
                        </span>
                </div>
                <div style={{position:"relative",verticalAlign:"middle",marginBottom:"30px"}}>
                    <span className="frontitem2">参会指南:</span>
                    <span className="backitem2">
                         <div className="editor-wrapper">
                                <BraftEditor {...editorProps} initialContent={activity.activityGuide}
                                             onChange={(content)=>{activity.activityGuide=content}}/>
                            </div>
                        </span>
                </div>
                <div style={{position:"relative",verticalAlign:"middle",marginBottom:"30px"}}>
                    <span className="frontitem2">活动日程:</span>
                    <span className="backitem2">
                          <div className="editor-wrapper">
                                <BraftEditor {...editorProps} initialContent={activity.schedule}
                                             onChange={(content)=>{activity.schedule=content}}/>
                            </div>
                        </span>
                </div>
                <div style={{position:"relative",verticalAlign:"middle",marginBottom:"10px"}}>
                    <span className="frontitem2">嘉宾介绍:</span>
                    <span className="backitem2">
                         <div className="editor-wrapper">
                                <BraftEditor {...editorProps} initialContent={activity.guestInfo}
                                             onChange={(content)=>{activity.guestInfo=content}}/>
                            </div>
                        </span>
                </div>
                <FormItem {...tailFormItemLayout}>
                    <Button size="large" type="primary" htmlType="submit"  disabled={this.hasErrors(getFieldsError())||store.activity.imagePath===undefined}>{this.props.id==-1?"立即创建":"确认修改"}</Button>
                </FormItem>
            </Form>):""}
            </div>
        );
    }
}
const EditActivity = Form.create()(EditActivities);

export default EditActivity